Accessing Elements and Exploring Different Methods
Lists in Python offer various ways to access elements and retrieve information. Here's a detailed breakdown of common methods:
1. Basic Accessing by Index
✦ The most fundamental way to access elements is by using zero-based indexing within square brackets ([]).
✦ The first element has index 0, the second has index 1, and so on.
Accessing element in a list in python
shopping_list = ["bread", "milk", "eggs"]
first_item = shopping_list[0]
last_item = shopping_list[-1]
print(first_item)
print(last_item)
Output
bread
eggs
2. Slicing for Sublist Extraction
Similar to strings, lists support slicing to extract a sublist (a portion of the original list).
Use the syntax [start:end:step]:
✦
start: Index of the first element to include (defaults to 0).
✦
end: Index of the character after the last element to include (not included in the sublist).
✦
step (optional): Number of steps to take between included elements (defaults to 1, including every element).
Slicing list and get sublist example in python
fruits = ["apple", "banana", "orange", "mango"]
first_two_fruits = fruits[0:2]
last_two_fruits = fruits[-2:]
# Extract every other element (step of 2)
every_other_fruit = fruits[::2]
print(first_two_fruits)
print(last_two_fruits)
print(every_other_fruit)
Output
['apple', 'banana']
['orange', 'mango']
['apple', 'orange']
3. Negative Indexing for Convenience
✦ Python allows negative indexing, starting from the end of the list.
✦ -1 refers to the last element, -2 to the second-last element, and so on.
Getting value in list by negative index in python
colors = ["red", "green", "blue", "purple"]
second_to_last_color = colors[-2]
print(second_to_last_color)
Output
blue
4. in Operator for Membership Testing
✦ Check if an element exists within the list using the in operator.
Checking elements availability using (in) operator in python
fruits = ["apple", "banana", "orange", "mango"]
is_apple_in_list = "apple" in fruits
print(is_apple_in_list)
is_grape_in_list = "grape" in fruits
print(is_grape_in_list)
Output
True
False
5. index() Method for Finding Element Position
✦ The index(x) method returns the lowest index of a specified element (x).
✦ It raises a ValueError if the element is not found.
Finding position of element in a list in python
fruits = ["apple", "banana", "orange", "mango"]
position_of_banana = fruits.index("banana")
print(position_of_banana)
# fruits.index("grape") # Raises ValueError (grape not found)
Output
1
Choosing the Right Access Method
✦ For simple access based on position, use indexing.
✦ For extracting sublists, slicing is the way to go.
✦ Use negative indexing for convenience when working with the end of the list.
✦ Employ the in operator to check element existence.
✦ Leverage the index() method to find the position of an element (but handle potential ValueError).